"""
用途：根据指定的testcases_name.txt文件创建测试计划
备注：下述参数需要进行指定
         :param plan_name: 测试计划名称
         :param testcases_type: 用例类型
"""
import time
import json
import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service


def get_kylin_testcases(testcases_type):
    """
    获取奇林平台用例属性
    :param testcases_type:
    :return:
    """
    # Chrome drive地址
    chromedriver_path = 'C:\Program Files\Google\Chrome\Application\chromedriver.exe'
    service = Service(chromedriver_path)
    option = webdriver.ChromeOptions()
    # 不弹出chrome浏览器
    option.add_argument("headless")
    browser = webdriver.Chrome(service=service, options=option)

    # 进入登录页面
    browser.get("http://10.16.8.8:18080/#/login")
    time.sleep(0.1)
    browser.find_element(By.ID, 'username').send_keys("zjf01")  # 填入用户名
    time.sleep(0.1)
    browser.find_element(By.ID, 'pwd').send_keys("abcd1234.")  # 填入密码
    time.sleep(0.1)
    browser.find_element(By.ID, "loginBtn").click()  # 填入密码
    time.sleep(1)

    # 进入脚本页面
    browser.get("http://10.16.8.8:18080/#/scripter")
    time.sleep(3)
    if testcases_type == "cvt-b":
        # 切换到 cvt-b项目
        browser.get(
            "http://10.16.8.8:18080/project/change?id=1714358491593&name=%E7%AB%99%E7%AB%AF%E7%BD%91%E9%A1%B5%E6%B5%8B%E8%AF%95_CVT_B")
    elif testcases_type == "cvt-a":
        # 切换到 cvt-a项目
        browser.get(
            "http://10.16.8.8:18080/project/change?id=1678877987831&name=%E7%AB%99%E7%AB%AF%E7%BD%91%E9%A1%B5%E6%B5%8B%E8%AF%95")
    else:
        print("type错误：{}".format(type))

    time.sleep(1)
    # 进入获取脚本属性页面
    browser.get("http://10.16.8.8:18080/scripter/list?type=scripter")
    time.sleep(1)
    # 获取页面源代码，xpath提取数据
    element = browser.find_element(By.XPATH, "/html/body/pre")
    list_data = json.loads(element.text)
    # print(list_data)

    filter_list = []
    for data in list_data:
        if data.get("type"):
            state = data.get("type").split(",")[2]
            # 如果用例状态为公共或者废弃，不添加到新列表中
            # 3:开发
            # 99：公共
            # 6：废弃
            if state == "99" or state == "6" or state == "3":
                # filter_list.append(data)
                continue
            else:
                filter_list.append(data)
        else:
            filter_list.append(data)
    cookie_data = browser.get_cookies()[0].get("value")
    browser.close()
    # print(filter_list)
    print("type:{},用例条数：{}".format(testcases_type, len(filter_list)))
    return filter_list, cookie_data


def get_list_testcases(testcases_type):
    """
    根据testcases_name.txt文件组装数据结构
    :param testcases_type:
    :return:
    """
    filter_list, cookie_data = get_kylin_testcases(testcases_type)
    # print(filter_list)
    with open("./testcases_name.txt", "r") as f:
        list_name = f.readlines()

    list_testcases = []
    for name in list_name:
        name = name.strip()
        # print(name)
        for filter in filter_list:
            if name in filter.get("name"):
                # 获取所以奇林用例接口ui属性错误，此处全部设置为1
                list_testcases.append({"id": filter.get("id"), "name": filter.get("name"), "ui": 1,
                                       "system": filter.get("system")})
    return list_testcases, cookie_data


def create_test_plan(plan_name, testcases_type):
    """
    创建奇林平台测试计划
    :param plan_name: 测试计划名称
    :param testcases_type: 用例类型
    :return:
    """
    list_testcases, cookie_data = get_list_testcases(testcases_type)
    print(list_testcases)
    headers = {
        "Accept": "application/json, text/plain, */*",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
        "Connection": "keep-alive",
        "Content-Length": "1506",
        "Content-Type": "application/json;charset=UTF-8",
        "Cookie": "JSESSIONID={}".format(cookie_data),
        "Host": "10.16.8.8:18080",
        "Origin": "http://10.16.8.8:18080",
        "Referer": "http://10.16.8.8:18080/",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0"
    }

    dict_data = {"id": "", "a": plan_name, "index": 0, "webDetail": 1, "logLevel": 0, "saveMode": 2,
                 "printIP": 0, "thread": 0, "justFirst": 0, "tcp": 0, "chart": 0, "ipSpoof": 0, "isUI": False, "app": 0,
                 "isApi": False, "ignoreResource": 0, "dns": {"enable": 0, "ip": ""},
                 "timer": {"enable": 0, "time": ""}, "threshold": [], "monitor": [],
                 "scripts": list_testcases,
                 "browser": [],
                 "uiConfig": {"close": True, "http": True, "log": True, "force": False, "load": False, "load2": 0,
                              "cpu": 25, "startTime": 0, "endTime": 0, "loopTime": 0, "loopTimes": 1, "failTimes": 1,
                              "remember": True, "global": 1, "video": 0, "info": 0, "clear": 0, "proxy": 0,
                              "baseline": 1, "mockIndex": 0, "install": 0, "app": "", "appDes": "", "lastRun": 1,
                              "justFail": 0, "agentMonitor": False}, "monitorItem": [],
                 "rendezvous": {"rendezvousEnable": 0, "policy": 1, "policyUsers_Percent": 10}, "testcaseTasks": [
            {"name": "task", "api": 0,
             "model": {"isCaps": 0, "modelType": 1, "caps": 2, "limit": 2, "keepTime": 1, "step": 1, "loopTime": 0,
                       "runTime": 5, "chooseType": 0, "totalUsers": "2", "percents": []}, "loadAgent": []}],
                 "des": ""}

    res = requests.post(
        "http://10.16.8.8:18080/controller/save?type=0&ui=false&id=&name={}&module=1&dial=0&assetProject=undefined".format(
            plan_name), headers=headers, data=json.dumps(dict_data))
    print(res)
    print(res.content.decode("utf-8"))
    assert res.status_code == 200


if __name__ == '__main__':
    filter_list, _ = get_kylin_testcases("cvt-b")
    print(filter_list)
    # get_list_testcases("cvt-b")
    # create_test_plan("1111", "cvt-b")
    create_test_plan("115终端测试", "cvt-a")
